const { SERVER_HOST, APP_PORT } = require('../config/config.default')
const path = require('path')

const uploadUrl = SERVER_HOST + ':' + APP_PORT + "/upload";

class CommonController {
    // 上传文件
    async upload_file(ctx) {
        // 获取上传文件
        const files = ctx.request.files.files;
        console.log('----------', files)
        let urlArr = []

        // 多文件
        if (files.length) {
            for (let file of files) {
                let basename = path.basename(file.path)
                let baseFile = file.path.split("upload")[1]
                let url = uploadUrl + `/${baseFile}`
                urlArr.push({
                    name: basename,
                    url: url
                })
            }
        } else { // 单文件
            let basename = path.basename(files.path)
            let baseFile = files.path.split("upload")[1]
            let url = uploadUrl + `/${baseFile}`
            urlArr.push({
                name: basename,
                url: url
            })
        }

        console.log(urlArr)
        const paths = JSON.stringify(urlArr)

        if (urlArr.length) {
            ctx.body = {
                url: urlArr,
                code: 200,
                message: '上传成功'
            };
        }

    }
}

module.exports = new CommonController()